package com.business.lgh.naocs.naming.misc;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.business.lgh.nacos.api.naming.pojo.Instance;
import com.business.lgh.naocs.naming.consistency.Record;
import com.business.lgh.naocs.naming.consistency.ephemeral.distro.DataStore;
import com.business.lgh.naocs.naming.core.pojo.Instances;
import okhttp3.*;
import okhttp3.internal.http.HttpMethod;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.util.Map;

/**
 * @author lgh
 * @version V1.0
 * @Package com.business.lgh.naocs.naming.misc
 * @date 2020/6/29 4:59 下午
 */
public class NamingProxy {

    public static final MediaType JSON_TYPE = MediaType.parse("application/json; charset=utf-8");


    public static DataStore syncGetDataStore(String serverAdress) throws IOException, ClassNotFoundException {
        OkHttpClient client = new OkHttpClient();
        String url = "http://" + serverAdress + "/nacos/v1/ns/distro/getAllDatums";
        Request request = new Request.Builder().url(url).build();
        Response resp = client.newCall(request).execute();
        if (resp.isSuccessful()) {
            String content = resp.body().string();
            return JSON.parseObject(content,DataStore.class);
        }
        return null;
    }

    public static boolean syncData(String serverAdress,Map<String,Datum> values) throws IOException, ClassNotFoundException {
        OkHttpClient client = new OkHttpClient();
        String url = "http://" + serverAdress + "/nacos/v1/ns/distro/datum";
        String content = JSONArray.toJSONString(values);
        RequestBody body = RequestBody.create(JSON_TYPE, content);
        Request request = new Request.Builder().url(url).put(body).build();
        Response resp = client.newCall(request).execute();
        if (resp.isSuccessful()) {
           return true;
        }
        return false;
    }

    static class ParamParse {

        public static DataStore parseResult(String json) {
            DataStore dataStore = new DataStore();
//            JSONObject
//            JSONObject root=new JSONObject.parse(json);
//            dataStore.setDatasource(stringDatumMap);
            return dataStore;
        }
    }
}
